package com.xoa.service.rms.impl;

import com.xoa.dao.rms.RmsFileMapper;
import com.xoa.dao.rms.RmsLendMapper;
import com.xoa.dao.rms.RmsRollMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.model.rms.*;
import com.xoa.model.users.Users;
import com.xoa.service.rms.RmsLendService;
import com.xoa.util.CookiesUtil;
import com.xoa.util.DateFormat;
import com.xoa.util.ToJson;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.page.PageParams;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class RmsLendServiceImpl implements RmsLendService {
    @Autowired
    private RmsLendMapper rmsLendMapper;
    @Autowired
    private UsersMapper usersMapper;
@Autowired
private RmsRollMapper rmsRollMapper;
    @Autowired
    private RmsFileMapper rmsFileMapper;
    /**
     * 郭心雨
     * 2018.07.31
     * 条件查询列表
     * 2018.07.31
     */
    @Override
    public ToJson selRmsLend(String userId,String allow,Integer page,Integer pageSize,Boolean useFlag) {
        ToJson<RmsLend> toJson =new ToJson<>();
        PageParams params=new PageParams();
        params.setUseFlag(useFlag);
        params.setPageSize(pageSize);
        params.setPage(page);
        Map<String,Object> map =new HashMap<>();
        map.put("userId",userId);
        map.put("allow",allow);
        map.put("page",params);
        List<RmsLend> lendList=rmsLendMapper.selRmsLend(map);
        for (RmsLend rmsLend:lendList){
            String uaername=usersMapper.getUsernameByUserId(rmsLend.getUserId());
            String approve=usersMapper.getUsernameByUserId(rmsLend.getApprove());
            String opreator=usersMapper.getUsernameByUserId(rmsLend.getOperator());
            rmsLend.setApprove(approve);
            rmsLend.setOperator(opreator);
            rmsLend.setUserId(uaername);
        }
        if(lendList.size()>0){
            toJson.setFlag(0);
            toJson.setMsg("ok");
            toJson.setObj(lendList);
            toJson.setTotleNum(params.getTotal());
        }else{
            toJson.setFlag(1);
            toJson.setMsg("err");
        }
        return toJson;
    }
    /**
     * 郭心雨
     * 2018.07.31
     * 更改文件借阅状态（归还，批准，不批）
     */
    @Override
    public ToJson modifyRmsLendById(String operator,String deleteFlag,String allow,Integer lendId,String returnTime,String allowTime) {
        ToJson<RmsLend> toJson =new ToJson<>();
        Map<String,Object> map =new HashMap<>();
        map.put("deleteFlag",deleteFlag);
        map.put("allow",allow);
        map.put("lendId",lendId);
        map.put("operator",operator);
//        '允许状态(0-待批准借阅,1-已批准借阅,2-未批准借阅,3-已归还借阅)',
        if(allow!=null&&!("").equals(allow)){
            if(allow.equals("3")){
                //修改归还时间
                map.put("returnTime",allow);
            }
            if(allow.equals("1")||allow.equals("2")){
                //修改审批时间
                map.put("allowTime",allow);
            }
            if(allow.equals("0")){
                //修改申请时间
                map.put("lendTime",allow);
            }
        }
        int count=rmsLendMapper.modifyRmsLendById(map);
        if(count>0){
            toJson.setFlag(0);
            toJson.setMsg("ok");
        }else{
            toJson.setFlag(1);
            toJson.setMsg("err");
        }
        return toJson;
    }
    /**
     * 郭心雨
     * 2018.08.01
     * 点击借阅,增加一条借阅信息
     */
    @Override
    public ToJson addRmsLend(RmsLend rmsLend) {
        ToJson<RmsLend> toJson =new ToJson<>();
        PageParams params=new PageParams();
//        rmsLend.setAllow("2");
        int count=rmsLendMapper.insertSelective(rmsLend);
        if(count>0){
            toJson.setObj1(count);
            toJson.setFlag(0);
            toJson.setMsg("ok");
        }else{
            toJson.setFlag(1);
            toJson.setMsg("err");
        }
        return toJson;
    }
    /**
     * 批量添加
     * 郭心雨
     * 2018.08.14
     */
    public ToJson insertLensd(HttpServletRequest request, Integer[] fileIds) {
        ToJson<RmsLend> toJson =new ToJson<>();
        Users users= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
//        List<RmsLend> list=(List<RmsLend>) JSONArray.toList(JSONArray.fromObject(jsonStr), RmsLend.class);
        List<RmsLend> list=new ArrayList<>();
        for(Integer fileId:fileIds){
            RmsLend rmsLend=new RmsLend();
            rmsLend.setUserId(users.getUserId());
            rmsLend.setApprove(users.getUserId());
            rmsLend.setFileId(fileId);
            rmsLend.setAllow("2");
            list.add(rmsLend);
        }
        Map<String,Object> map=new HashMap<>();
        map.put("rmsLend",list);
        int count=rmsLendMapper.insertLensd(map);
        if(count>0){
            toJson.setFlag(0);
            toJson.setMsg("ok");
        }else{
            toJson.setFlag(1);
            toJson.setMsg("err");
        }
        return toJson;
    }
    /**
     * 郭心雨
     * 模糊动态查询
     * 2018-08-14
     */
    public ToJson selAllLendBy(Integer page,Integer pageSize,Boolean useFlag,RmsFile rmsFile, String roomName, String rollName){
        ToJson<RmsFileWithBLOBs> toJson =new ToJson<>();
        Map<String,Object> map =new HashMap<>();
        PageParams pageParams=new PageParams();
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        pageParams.setUseFlag(useFlag);
        map.put("rmsFile",rmsFile);
        map.put("roomName",roomName);
        map.put("rollName",rollName);
        map.put("pageParams",pageParams);
        List<RmsFileWithBLOBs> fileList=rmsLendMapper.selAllLendBy(map);
        if (fileList.size()>0){
            toJson.setObj(fileList);
            toJson.setTotleNum(pageParams.getTotal());
            toJson.setMsg("ok");
            toJson.setFlag(0);
        }else{
            toJson.setMsg("err");
            toJson.setFlag(1);
        }
        return toJson;
    }


    @Override
    public ToJson<RmsRollWithBLOBs> rollCount(RmsRollWithBLOBs rmsRollWithBLOBs, PageParams pageParams) {
        ToJson<RmsRollWithBLOBs> json = new ToJson<RmsRollWithBLOBs>();
        try{
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("page",pageParams);
            map.put("rollCode",rmsRollWithBLOBs.getRollCode());
            map.put("roomId",rmsRollWithBLOBs.getRoomId());
            map.put("beginDate",rmsRollWithBLOBs.getBeginDate());
            map.put("beginDate2",rmsRollWithBLOBs.getBeginDate2());
            map.put("endDate",rmsRollWithBLOBs.getEndDate());
            map.put("endDate2",rmsRollWithBLOBs.getEndDate2());
            map.put("deadBeginDate",rmsRollWithBLOBs.getDeadBeginDate());
            map.put("deadEndDate",rmsRollWithBLOBs.getDeadEndDate());
            map.put("categoryNo",rmsRollWithBLOBs.getCategoryNo());
            map.put("archiveNo",rmsRollWithBLOBs.getArchiveNo());
            // 缩微号
            map.put("microNo",rmsRollWithBLOBs.getMicroNo());
            // 凭证编号开始
            map.put("certificateStart",rmsRollWithBLOBs.getCertificateStart());
            map.put("certificateStart2",rmsRollWithBLOBs.getCertificateStart2());
            // 凭证编号截止
            map.put("certificateEnd",rmsRollWithBLOBs.getCertificateEnd());
            map.put("certificateEnd2",rmsRollWithBLOBs.getCertificateEnd2());
            // 页数查询
            map.put("rollPage",rmsRollWithBLOBs.getRollPage());
            map.put("rollPage2",rmsRollWithBLOBs.getRollPage2());
            map.put("remark",rmsRollWithBLOBs.getRemark());
            map.put("rollName",rmsRollWithBLOBs.getRollName());
            map.put("years",rmsRollWithBLOBs.getYears());
            map.put("secret",rmsRollWithBLOBs.getSecret());
            map.put("catalogNo",rmsRollWithBLOBs.getCatalogNo());
            map.put("boxNo",rmsRollWithBLOBs.getBoxNo());
            map.put("certificateKind",rmsRollWithBLOBs.getCertificateKind());
            map.put("deptId",rmsRollWithBLOBs.getDeptId());
            List<RmsRollWithBLOBs> RmsRollWithBLOBsList = rmsRollMapper.query(map);
            if(RmsRollWithBLOBsList.size()>0){
                for (RmsRollWithBLOBs rollWithBLOBs:RmsRollWithBLOBsList){
                    //案卷号
                    Map<String, Object> map1 = new HashMap<String, Object>();
                    map1.put("rollId", rollWithBLOBs.getRollId());
                    map1.put("delStatus", 0);
                    List<RmsFileWithBLOBs> query = rmsFileMapper.query(map1);
                    rollWithBLOBs.setAnjuanCount(query.size());
                }
            }
            json.setTotleNum(pageParams.getTotal());
            json.setObj(RmsRollWithBLOBsList);
            json.setFlag(0);
            json.setMsg("ok");
        }catch (Exception e){
            json.setFlag(1);
            json.setMsg("err");
        }
        return json;
    }
    @Override
    public ToJson<RmsFileWithBLOBs> fileJieYueCount(RmsFileWithBLOBs rmsFileWithBLOBs, PageParams pageParams) {
        ToJson<RmsFileWithBLOBs> json = new ToJson();
        try {
            Map<String, Object> map = new HashMap();
            map.put("page", pageParams);
            List<RmsFileWithBLOBs> query = rmsFileMapper.query(map);
            if(query.size()>0){
                for(RmsFileWithBLOBs rmsFileWithBLOBs1:query){
                    int count=rmsLendMapper.selFileJieYueCount(rmsFileWithBLOBs1.getFileId());
                    rmsFileWithBLOBs1.setFileCount(count);
                }
            }
            json.setObj(query);
            json.setTotleNum(pageParams.getTotal());
            json.setFlag(0);
            json.setMsg("ok");
        } catch (Exception e) {
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg("err");
        }
        return json;
    }

    @Override
    public ToJson selRmsLendByJieYe(Integer fileId, String allow, Integer page, Integer pageSize, Boolean useFlag) {
        ToJson<RmsLend> toJson =new ToJson<>();
        PageParams params=new PageParams();
        params.setUseFlag(useFlag);
        params.setPageSize(pageSize);
        params.setPage(page);
        Map<String,Object> map =new HashMap<>();
        map.put("fileId",fileId);
        map.put("allow",allow);
        map.put("page",params);
        List<RmsLend> lendList=rmsLendMapper.selRmsLendByJieYe(map);
        for (RmsLend rmsLend:lendList){
            String uaername=usersMapper.getUsernameByUserId(rmsLend.getUserId());
            String approve=usersMapper.getUsernameByUserId(rmsLend.getApprove());
            String opreator=usersMapper.getUsernameByUserId(rmsLend.getOperator());
            rmsLend.setApprove(approve);
            rmsLend.setOperator(opreator);
            rmsLend.setUserId(uaername);
        }
        if(lendList.size()>0){
            toJson.setFlag(0);
            toJson.setMsg("ok");
            toJson.setObj(lendList);
            toJson.setTotleNum(params.getTotal());
        }else{
            toJson.setFlag(1);
            toJson.setMsg("err");
        }
        return toJson;
    }

    /**
     * 根据allow 状态修改  审批人 审批时间 审批状态
     * @param rmsLend
     * @return
     */
    @Override
    public Integer updateAllow(RmsLend rmsLend) {
        //获取登录用户
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionCookie);

        //审批人
        rmsLend.setOperator(users.getUserId());
        //审批时间
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        rmsLend.setAllowTime(sf.format(new Date()));



        return rmsLendMapper.updateByPrimaryKeySelective(rmsLend);
    }

    /**
     * 根据审核状态查询
     * @param allow
     * @return
     */
    @Override
    public List<RmsLend> selectAllow(String allow) {
        return rmsLendMapper.selectAllow(allow);
    }

    /**
     * 删除  根据lendId去删除
     * @param lendId
     * @return
     */
    @Override
    public Integer deleteFlag(Integer lendId) {
        return rmsLendMapper.deleteFlag(lendId);
    }

    /**
     * 根据 lendId 查看详情
     * @param lendId
     * @return
     */
    @Override
    @RequestMapping("/selectByLend")
    @ResponseBody
    public RmsLend selectByLend(Integer lendId) {

        RmsLend rmsLend = rmsLendMapper.selectByPrimaryKey(lendId);
        if ("0".equals(rmsLend.getType())){
            rmsLend = rmsLendMapper.selectFile(rmsLend);
            rmsLend.setName(rmsLend.getFileTitle());
        }else {
           rmsLend = rmsLendMapper.selectRoll(rmsLend);
           rmsLend.setName(rmsLend.getRollName());
        }
        return rmsLend;
    }

    /**
     * 分装查询数据
     * @param page
     * @param pageSize
     * @param useFlag
     * @param map
     * @return
     */
    @Override
    public List<RmsLend> selectByCount(Integer page, Integer pageSize, Boolean useFlag, Map map , RmsLend rmsLend) {
        PageParams pageParams = new PageParams();
        pageParams.setUseFlag(useFlag);
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        map.put("page",pageParams);
        map.put("obj" ,rmsLend);

        List<RmsLend> rmsLendList = rmsLendMapper.queryCount(map);
        List<RmsLend> rmsLends = new ArrayList<>();
        for (RmsLend rmsLend1 : rmsLendList) {
            if (rmsLend1.getType().equals("0")){
                rmsLend1 = rmsLendMapper.selectAndFileId(rmsLend1);
                rmsLend1.setName(rmsLend1.getFileTitle());
            }
            if (rmsLend1.getType().equals("1")){
                rmsLend1 = rmsLendMapper.selectAndRollId(rmsLend1);
                rmsLend1.setName(rmsLend1.getRollName());
            }
            rmsLends.add(rmsLend1);
        }

        return rmsLends;
    }

    //模糊查询
    @Override
    public List<RmsLend> queryByCount(Integer page, Integer pageSize, Boolean useFlag, Map map, RmsFile rmsFile, RmsRoll rmsRoll,RmsLend rmsLend) {
        PageParams pageParams = new PageParams();
        pageParams.setUseFlag(useFlag);
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        map.put("page",pageParams);
        map.put("obj",rmsLend);

        //存放模糊查询出的数据
        List<RmsLend> rmsList = new ArrayList<>();
        List<RmsLend> rmsLendList = rmsLendMapper.selectByFile(rmsLend);
        rmsList.addAll(rmsLendList);
         List<RmsLend> rmsLendLists = rmsLendMapper.selectByRoll(rmsLend);
        rmsList.addAll(rmsLendLists);


        map.put("list",rmsList);
        //带上分页
        List<RmsLend> select = rmsLendMapper.select(map);
        List<RmsLend> rmsLends = new ArrayList<>();
        //封装数据
        for (RmsLend rmsLend1 : select) {//(0-数据来源于文件管理 ，1-数据来源于案卷管理)',
            if (rmsLend1.getType().equals("0")) {
                rmsLend = rmsLendMapper.selectAndFileId(rmsLend1);
                rmsLend1.setName(rmsLend.getFileTitle());
            }
            if (rmsLend1.getType().equals("1")) {
                rmsLend = rmsLendMapper.selectAndRollId(rmsLend1);
                rmsLend1.setName(rmsLend.getRollName());
                rmsLend1.setRollId(rmsLend.getFileId());
            }
            rmsLends.add(rmsLend1);
        }
        return rmsLends;
    }

    //我的借阅
    public List<RmsLend> select(Integer page, Integer pageSize, Boolean useFlag, Map map , RmsLend rmsLend){
        PageParams pageParams  = new PageParams();
        pageParams.setUseFlag(useFlag);
        pageParams.setPageSize(pageSize);
        pageParams.setPage(page);
        map.put("page",pageParams);

        //获取登录用户
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionCookie);
        rmsLend.setUserId(users.getUserId());

        map.put("obj",rmsLend);

        List<RmsLend> rmsLendList = rmsLendMapper.queryCount(map);

        List<RmsLend> rmsLends = new ArrayList<>();
        for (RmsLend lend : rmsLendList) {
            if (lend.getType().equals("0")){
                lend = rmsLendMapper.selectAndFileId(lend);
                lend.setName(lend.getFileTitle());
            }
            if (lend.getType().equals("1")){
                lend = rmsLendMapper.selectAndRollId(lend);
                lend.setName(lend.getRollName());
            }
            rmsLends.add(lend);
        }

        return rmsLends;
    }

    /**
     * 查询文件管理
     * @return
     */
    @Override
    public List<RmsFile> selectAndFile() {
        return null;
    }


}
